package top.cptr.simpleRpc.rpccore.exception;

import cn.hutool.http.ContentType;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.http.server.filter.HttpFilter;
import com.alibaba.fastjson.JSON;
import com.sun.net.httpserver.Filter;
import top.cptr.simpleRpc.rpccore.command.rpc.ResultError;

import java.io.IOException;

/**
 * @author Tiger_L
 * @version 1.0
 * @description 错误拦截器
 * @date 2024/1/4 16:41
 */
public class ExceptionFilter implements HttpFilter {

    @Override
    public void doFilter(HttpServerRequest req, HttpServerResponse res, Filter.Chain chain) throws IOException {
        try {
            chain.doFilter(req.getHttpExchange());
        } catch (Exception e) {
            res.setContentType(ContentType.JSON.getValue());
            res.send(HttpStatus.HTTP_INTERNAL_ERROR);
            ResultError resultError = new ResultError();
            resultError.setJsonrpc("2.0");
            resultError.setError(e.getMessage());
            res.write(JSON.toJSONBytes(resultError));
        }
    }
}
